package com.ybear.ybcomponent.widget.dialog

import android.Manifest
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.IntDef
import androidx.annotation.RequiresPermission
import androidx.annotation.StyleRes
import androidx.core.content.ContextCompat
import com.ybear.ybcomponent.R
import com.ybear.ybcomponent.widget.shape.helper.IShape

class WindowStyle(private val mContext: Context, parent: IShape?) {
    @IntDef(
        GradientDrawable.RECTANGLE,
        GradientDrawable.OVAL,
        GradientDrawable.LINE,
        GradientDrawable.RING
    )
    @Retention(AnnotationRetention.SOURCE)
    annotation class Shape

    val cornerRadius: CornerRadius = CornerRadius( parent )
    var backgroundDrawable: Drawable? = null
    var backgroundDrawableByRoot: Drawable? = null
    var dimAmount = -1f
    var gravity = Gravity.CENTER

    @set:RequiresPermission(Manifest.permission.SYSTEM_ALERT_WINDOW)
    var isSystemDialog = false

    @StyleRes
    var animations = 0

    init {
        setShape(GradientDrawable.RECTANGLE)
        setBackgroundColorInt( Color.WHITE )
    }

    fun setBackgroundDrawableResource(@DrawableRes res: Int) {
        backgroundDrawable = ContextCompat.getDrawable(mContext, res)
    }

    fun setBackgroundColor(@ColorRes color: Int) {
        setBackgroundColorInt( ContextCompat.getColor( mContext, color ) )
    }

    fun setBackgroundColorInt(@ColorInt color: Int) {
        val drawable = GradientDrawable()
        drawable.setColor( color )
        backgroundDrawable = drawable
    }

    fun setStroke(width: Int, @ColorInt color: Int) {
        if( backgroundDrawable == null ) setBackgroundColorInt( Color.WHITE )
        if (backgroundDrawable is GradientDrawable) {
            (backgroundDrawable as GradientDrawable).setStroke(width, color)
        }
    }

    fun setShape(@Shape shape: Int) {
        if( backgroundDrawable == null ) setBackgroundColorInt( Color.WHITE )
        if ( backgroundDrawable is GradientDrawable ) {
            ( backgroundDrawable as GradientDrawable ).shape = shape
        }
    }

    fun setBackgroundDrawableResourceByRoot(@DrawableRes res: Int) {
        backgroundDrawableByRoot = ContextCompat.getDrawable( mContext, res )
    }

    fun setBackgroundColorByRoot(@ColorRes color: Int) {
        setBackgroundColorIntByRoot( ContextCompat.getColor( mContext, color ) )
    }

    fun setBackgroundColorIntByRoot(@ColorInt color: Int) {
        val drawable = GradientDrawable()
        drawable.setColor( color )
        backgroundDrawableByRoot = drawable
    }
}